package com.example.aigc_education.integration.threeparty;


import com.example.aigc_education.domain.vo.FilePathVO;
import com.example.aigc_education.integration.AliOssIntegration;
import com.example.aigc_education.utils.ResultUtil;
import com.example.aigc_education.utils.UUID;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;

/**
 *在第三方接口上根据我们需求对其代码调用进行调整
 */
@Slf4j
@Service
public class AliYunService {

    @Resource
    private AliOssIntegration aliOssIntegration;

    /**
     *
     * @param image 图片
     * @return
     */

    public ResultUtil uploadImage(MultipartFile image) {

        log.info("图片上传：{}",image);
        try {
            if (image.getSize() > 1024 * 1024 * 10) {
                return ResultUtil.error("图片大小不能大于20M");
            }
            //原始文件名
            String originalFilename = image.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (!(extension.equals(".jpg") || extension.equals(".png"))) {
                return ResultUtil.error("文件格式错误，请上传图片");
            }
            //构造新文件名称
            // 增加文件结构，按年月日区分文件
            // 使用 DateTimeFormatter 格式化 LocalDate
            String date = LocalDate.now().toString();
            String objectName = "image"+ "/" + date + "/" + UUID.randomUUID().toString() + extension;
            //文件的请求路径
            String filePath = aliOssIntegration.ossUpload(objectName,image.getBytes());
            return ResultUtil.success(FilePathVO.builder().fileUrl(filePath).build());
        } catch (IOException e) {
            log.error("图片上传失败：{}", e);
        }

        return ResultUtil.error("存储失败");
    }

    /**
     *
     * @param document 文档
     * @return
     */

    public ResultUtil uploadDocument(MultipartFile document) {

        log.info("文档上传：{}",document);
        log.info("文档大小：{}",document.getSize());
        if (document.getSize() > 1024 * 1024 * 30) {
            return ResultUtil.error("文档大小不能大于30M");
        }
        //原始文件名
        String originalFilename = document.getOriginalFilename();
        //截取原始文件名的后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!(extension.equals(".pdf") || extension.equals(".docx") || extension.equals(".doc"))) {
            return ResultUtil.error("文件格式错误，请上传文档");
        }
        //构造新文件名称
        // 增加文件结构，按年月日区分文件
        String date = LocalDate.now().toString();
        String objectName = "document"+ "/" + date + "/" + UUID.randomUUID().toString() + extension;

        try {

            // 找到该项目的运行位置
            String path = System.getProperty("user.dir");
            log.info("项目运行位置：{}", path);

            // 存一份至临时文件夹
            // File tempDir = new File(path + "\\temp"); //windows
            // File tempDir = new File(path + "/temp"); // linux
            // if (!tempDir.exists()) {
            //     tempDir.mkdirs();
            // }

            // // String localTmpPath = path + "\\temp\\" +UUID.randomUUID().toString() + extension; //windows
            // String localTmpPath = path + "/temp/" +UUID.randomUUID().toString() + extension;
            // 使用 Path API 处理文件路径
            Path projectRoot = Paths.get(System.getProperty("user.dir"));
            Path tempDir = projectRoot.resolve("temp");

            // 创建临时目录
            try {
                Files.createDirectories(tempDir);
            } catch (IOException e) {
                log.error("Failed to create temp directory", e);
                return ResultUtil.error("Failed to create temp directory");
            }

            String filename = UUID.randomUUID().toString() + extension;
            Path localTmpPath = tempDir.resolve(filename);
            // File localTmpFile = new File(localTmpPath);
//            document.transferTo(localTmpFile);
            // Files.copy(document.getInputStream(), localTmpFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            Files.copy(document.getInputStream(), localTmpPath, StandardCopyOption.REPLACE_EXISTING);

            System.out.println("document.getBytes() is length = " + document.getBytes().length);
            //文件的请求路径
            String filePath = aliOssIntegration.ossUpload(objectName,document.getBytes());
            log.info("文档上传成功：{}", filePath);
            log.info("文档本地路径：{}", localTmpPath.toString());
            return ResultUtil.success(FilePathVO.builder().fileUrl(filePath).localTmpPath(localTmpPath.toString()).build());
        } catch (IOException e) {
            log.error("文档上传失败：{}", e);
        }

        return ResultUtil.error("存储失败");
    }


}
